<?php
namespace app\web\model;

use cubox\Model;
use cubox\model\Tree;
use cubox\Cubox;

class Part extends Model{

    use Tree;

    public function __construct()
    {
        $this->treeCacheName = $this->table.'_tree';
    }
    
    public function getRoute($part_id){
        static $routeData = array();

        if (isset($routeData[$part_id])) return $routeData[$part_id];

        $data = $this->getId($part_id);
        $route = '';
        if ($data['route']!=''){

            $route = $data['route'];

            if ($data['route_type']=='default'){
                $route = Cubox::url('web','index','part',['id'=>$part_id]);
            }

            if ($data['route_type']=='root'){
                $route = '/'. $route ;
            }

            if ($data['route_type']=='parent'){

                if ($data['parent_id']!=0){
                    $parent_route = $this->getRoute($data['parent_id']);

                    if ($parent_route!=''){
                        $route =  $parent_route.'/'. $route;
                    }
                }
                
            }
        }

        $routeData[$part_id] = $route;
        return $route;
    }

    public function frontData($part_id){
        static $frontData = array();

        if (isset($frontData[$part_id])){
            return $frontData[$part_id];
        }

        $data = $this->getId($part_id);
        if (!$data) return false;

        try{
            $param = json_decode($data['param'],true);
        }catch(\Exception $e){
            $param = array();
        }

        $re = $param;
        $re['title'] =  $data['title'];
        $re['row'] = $data;
        
        $pathList = $this->getTreePath($data['parent_id']);

        foreach($pathList as $key=>$val){
            $re['path'][] = $this->frontData($val[$this->key]);
        }
        $re['route'] =  $this->getRoute($part_id);
        $frontData[$part_id] = $re;
        return $re;
    }
}